package air.jason.com.porterduffxfermodetest.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.View;

import air.jason.com.porterduffxfermodetest.R;

/**
 * @DESC:
 * @Author: Jason
 * @Date: 16/8/25
 * @Time: 00:18
 */


/**
 * PorterDuff.Mode.SCREEN
 *          计算方式：[Sa + Da - Sa * Da, Sc + Dc - Sc * Dc] ：滤色
 */
public class ScreenView4 extends View {

    private Paint mPaint;
    private Bitmap mBitmapSrc;
    private PorterDuffXfermode mPorterDuffXfermode;
    private int x, y;
    private int screenW, screenH;

    public ScreenView4(Context context) {
        this(context, null);
    }

    public ScreenView4(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPorterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.SCREEN);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBitmapSrc = BitmapFactory.decodeResource(context.getResources(), R.drawable.a3);
        screenW = context.getResources().getDisplayMetrics().widthPixels;
        screenH = context.getResources().getDisplayMetrics().heightPixels;
        x = screenW / 2 - mBitmapSrc.getWidth() / 2;
        y = screenH / 2 - mBitmapSrc.getHeight() / 2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawColor(Color.WHITE);

        int sc = canvas.saveLayer(0, 0, screenW, screenH, null, Canvas.ALL_SAVE_FLAG);

        canvas.drawColor(0xcc1c093e);

        // 设置混合模式
        mPaint.setXfermode(mPorterDuffXfermode);

        // 再绘制源图
        canvas.drawBitmap(mBitmapSrc, x, y, mPaint);
        // 还原混合模式
        mPaint.setXfermode(null);
        // 还原画布
        canvas.restoreToCount(sc);
    }
}
